import wx from '../../subwe/bridge';
import WXPage from "../../subwe/page";
import { Index } from '../../apis/index.js';
import { openBluetoothAdapter, openBluetoothAdapterPeripheral, BLEConnectionMessage } from '../../utils/bluetooth';
const app = getApp();
const API = new Index();
import CONST from '../../utils/const';
import util, { BluetoothMac, BluetoothPowerMinute, formatTime } from '../../utils/util';
// import { openBluetoothAdapterPeripheral } from '../../utils/bluetooth'
import { onScan } from '../../utils/common';
import api, { goodsList } from '../../apis/api.js';
let computeOrderCostTime = null;
let bluetoothStatusTime = null;
const {
  baseUrl,
  yundianUrl
} = require("../../config");
function inArray(arr, key, val) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i][key] === val) {
      return i;
    }
  }
  return -1;
}
WXPage({
  data: {
    // 客服电话
    callPhone: '400-818-7978',
    loginInfo: {},
    orderInfo: {},
    devInfo: {},
    orderCost: {
      t: '0',
      money: '0.00'
    },
    custom: app.globalData.Custom,
    windowW: app.globalData.windowW,
    showPage: false,
    serviceList: [],
    hotServiceList: [],
    currentMenuIndex: 0,
    serviceMenuList: [],
    bulletin: '',
    imageUrl: `${app.globalData.imageUrl}`,
    continueInfo: {
      off: false,
      loading: false,
      isDisable: false,
      days: 1,
      price: 0,
      discountsAmount: 0,
      roomTypeId: 0
    },
    noticeList: [],
    notice: "",
    showAd: 1,
    // goodsType: []
    serviceSkipMap: {},
    isSuper: false,
    adUrl: 'https://zmapi.cnman.cn/static/fz/fz_zhejiang_hangzhouxihu.jpg',
    adUrlLinping: 'https://zmapi.cnman.cn/static/fz/fz_zhejiang_hangzhoulinping.jpg',
    adUrlhenyang: 'https://zmapi.cnman.cn/static/eydj.jpg',
    adUrlnanning: 'https://zmapi.cnman.cn/static/xm_gxnn.jpg',
    isShow: true,
    appId: "wx83aeeb3f73831de9"
  },
  onLoad(options) {
    app.toPageServiceHome(true);
    // this.getLoginToken();
    this.setData({
      showAd: wx.getStorageSync("showAd"),
      isSuper: app.globalData.isSuper
    });
  },
  handleSwiperChange({
    detail
  }) {
    this.setData({
      currentMenuIndex: detail.current
    });
  },
  getFixedRemindRss() {
    this.pageGotoGoodComent()
    // API.getFixedRemindRss({
    //   openid: this.data.loginInfo.openid
    // }).then(res => {
    //   if (res.result.length) return this.pageGotoGoodComent();
    //   this.messageEvaluateAlertAuthorization();
    // });
  },
  // 服务评价提醒授权
  messageEvaluateAlertAuthorization() {
    console.log('messageEvaluateAlertAuthorization');
    let tmplIds = ['a3Iv2WMm497jJETnzpSvET3gwAomvj01xHRhSDoW3S8'];
    let that = this;
    // wx.requestSubscribeMessage({
    //   tmplIds,
    //   success(res) {
    //     let params = {
    //       deviceSn: app.globalData.deviceSn,
    //       openid: that.data.loginInfo.openid
    //     };
    //     let acceptTemIds = [];
    //     for (let key in res) if (key !== 'errMsg') if (res[key] === 'accept') {
    //       acceptTemIds.push(key);
    //       params.templateId = key;
    //       API.fixedRemindRss(params).then(res => {
    //         console.log(res);
    //       });
    //     }
    //     params.templateId = acceptTemIds;
    //     that.pageGotoGoodComent();
    //     // if (acceptTemIds.length === 0) return
    //     // console.log(res)
    //     // wx.showModal({
    //     //   title: '提示',
    //     //   content: (countdownSecond / 3600 ) + '小时后，归还通知提醒',
    //     //   showCancel: false,
    //     //   success (res) {
    //     //     if (res.confirm) {
    //     //       console.log('用户点击确定')
    //     //     } else if (res.cancel) {
    //     //       console.log('用户点击取消')
    //     //     }
    //     //   }
    //     // })
    //   },
    //
    //   fail(err) {
    //     console.log("requestSubscribeMessage-err", err);
    //     that.pageGotoGoodComent();
    //   }
    // });
  },
  // 售货机下单页面
  toAutomateGoodsPage() {
    // wx.reportEvent("service_meituan_shouhuoji", {});
    let serviceDesc = "售卖服务";
    if (this.data.devInfo.prodType !== 3) serviceDesc = "当前设备不支持";
    if (!this.data.devInfo.automateGoodsList || !this.data.devInfo.automateGoodsList.length) serviceDesc = "暂未开通购买服务";
    let param = {
      deviceSn: this.data.devInfo.deviceSn,
      appId: this.data.appId,
      serviceType: 13,
      serviceDesc: serviceDesc
    };
    API.addServiceLog(param).then(res => {
      console.log("日志记录成功");
    });
    if (this.data.devInfo.prodType !== 3) return wx.showToast({
      title: '当前设备不支持',
      icon: 'none'
    });
    if (!this.data.devInfo.automateGoodsList || !this.data.devInfo.automateGoodsList.length) return wx.showToast({
      title: '暂未开通购买服务',
      icon: 'none'
    });
    let deviceSn = app.globalData.deviceSn;
    let placeId = this.data.devInfo.placeId;
    let mac = this.data.devInfo.bluetoothMac;
    wx.navigateTo({
      url: `/pages/automate/automate?placeId=${placeId}&deviceSn=${deviceSn}&mac=${mac}`
    });
  },
  getNoticeInfo() {
    API.getNoticeInfo({
      pageNo: 1,
      pageSize: 20,
      placeId: this.data.devInfo.placeId
    }).then(res => {
      this.setData({
        notice: res.result.data[0] && res.result.data[0].title
        // noticeList: res.result.data
      });
    });
  },

  startWifiToSystem() {
    wx.hideLoading();
    const {
      wifiPassword,
      wifiName
    } = this.data.devInfo;
    wx.connectWifi({
      SSID: wifiName.replace(/\s+/g, ''),
      password: wifiPassword ? wifiPassword : '',
      success: res => {
        console.log('WIFI连接成功-startwifitosystem', res);
        wx.showToast({
          title: 'WIFI连接成功',
          icon: 'success'
        });
      },
      fail: err => {},
      maunal: true
    });
  },
  startWifi() {
    var _this = this;
    const {
      wifiName,
      wifiPassword
    } = this.data.devInfo;
    my.connectWifi({
      SSID: wifiName.replace(/\s+/g, ''),
      password: wifiPassword ? wifiPassword : '',
      success: res => {
        wx.hideLoading();
        wx.showToast({
          title: 'WIFI连接成功',
          icon: 'success'
        });
      },
      fail: err => {
        console.log('wifi连接失败', err);
        if (err.errCode > 0) {
          _this.wifiError(err);
        } else {
          wx.showModal({
            title: 'WIFI连接失败',
            content: `WIFI名称：${_this.data.devInfo.wifiName || ''} / WIFI密码：${_this.data.devInfo.wifiPassword || ''}`,
            confirmText: '复制密码',
            cancelText: '取消',
            cancelColor: '#333',
            confirmColor: '#00A49A',
            success: res => {
              if (res.confirm) {
                //点击手动连接，自动复制密码
                wx.setClipboard({
                  text: _this.data.devInfo.wifiPassword,
                  success(res) {
                    wx.getClipboard({
                      success(res) {
                        console.log(res.text); // data
                      }
                    });

                    _this.startWifiToSystem();
                  }
                });
              } else if (res.cancel) {}
            }
          });
        }
      }
    });
  },
  connectedWifi() {
    // 先临时跳转至小电助手
    // wx.navigateToMiniProgram({
    //   appId: 'wxa2d02c6a1e8ffb24',
    //   path: 'pages/wifiService/wifiService?q=' + this.data.devInfo.deviceSn + '&t=zm'
    // })

    var _this = this;
    // wx.reportEvent("service_meituan_kefang", {});
    let serviceDesc = "连接WIFI";
    if (!_this.data.devInfo.wifiName) serviceDesc = "WIFI未配置";
    let param = {
      deviceSn: _this.data.devInfo.deviceSn,
      appId: _this.data.appId,
      serviceType: 0,
      serviceDesc: serviceDesc
    };
    API.addServiceLog(param).then(res => {
      console.log("日志记录成功");
    });
    if (!_this.data.devInfo.wifiName) return wx.showToast({
      title: 'WIFI未配置',
      icon: 'none'
    });
    wx.showLoading({
      title: 'WIFI连接中'
    });
    my.startWifi({
      success: res => {
        my.getConnectedWifi({
          success: res => {
            wx.hideLoading();
            console.log('获取已连接WIFI信息', res, _this.data.devInfo.wifiName);
            if (res.wifi.SSID !== _this.data.devInfo.wifiName.replace(/\s+/g, '')) {
              return _this.startWifi()
            }
            wx.showToast({
              title: 'WIFI连接成功',
              icon: 'success'
            });

          },
          fail: err => {
            _this.wifiError(err);
          }
        });
      },
      fail: err => {
        console.log('my.startWifi', err)
        _this.wifiError(err)
        wx.hideLoading();
      }
    });
  },
  wifiError(err) {
    console.log('WIFI连接错误-wifierr', err)
    wx.showModal(
        {
          title: `${err.errorMessage || '连接失败'}`
        })

    // if (err.errCode === 12001) {
    //   wx.hideLoading();
    //   wx.showModal({
    //     title: '当前系统不支持相关能力'
    //   });
    // }
    // if (err.errCode === 12002) {
    //   wx.hideLoading();
    //   wx.showModal({
    //     title: '密码错误'
    //   });
    // }
    // if (err.errCode === 12003) {
    //   wx.hideLoading();
    //   wx.showModal({
    //     title: '连接超时, 请查看是否打开GPS'
    //   });
    // }
    // if (err.errCode === 12004) {
    //   wx.hideLoading();
    //   wx.showModal({
    //     title: '重复连接 Wi-Fi'
    //   });
    // }
    // if (err.errCode === 12005) {
    //   wx.hideLoading();
    //   wx.showModal({
    //     title: '未打开 Wi-Fi 开关'
    //   });
    // }
    // if (err.errCode === 12006) {
    //   wx.hideLoading();
    //   wx.showModal({
    //     title: '未打开 GPS 定位开关'
    //   });
    // }
    // if (err.errCode === 12007) {
    //   wx.hideLoading();
    //   wx.showModal({
    //     title: '用户拒绝授权链接 Wi-Fi'
    //   });
    // }
    // if (err.errCode === 12008) {
    //   wx.hideLoading();
    //   wx.showModal({
    //     title: '无效 SSID'
    //   });
    // }
    // if (err.errCode === 12009) {
    //   wx.hideLoading();
    //   wx.showModal({
    //     title: '系统运营商配置拒绝连接 Wi-Fi'
    //   });
    // }
    // if (err.errCode === 12010) {
    //   wx.hideLoading();
    //   wx.showModal({
    //     title: 'WIFI不在范围内或系统其他错误' + err.errMsg
    //   });
    // }
    // if (err.errCode === 12011) {
    //   wx.hideLoading();
    //   wx.showModal({
    //     title: '应用在后台无法配置 Wi-Fi'
    //   });
    // }
    // if (err.errCode === 12013) {
    //   wx.hideLoading();
    //   wx.showModal({
    //     title: '系统保存的 Wi-Fi 配置过期，建议忘记 Wi-Fi 后重试'
    //   });
    // }
    // if (err.errCode === 12014) {
    //   wx.hideLoading();
    //   wx.showModal({
    //     title: '无效的 WEP / WPA 密码'
    //   });
    // }
    // return;
  },
  onShow() {
    setTimeout(() => this.setData({
      showPage: true
    }), 2800);
  },
  onScanFn() {
    wx.scanCode({
      scanType: ['qrCode'],
      success: res => {
        console.log(res)

        var result = res.result;
        let q = decodeURIComponent(result);
        app.globalData.deviceSn = util.getQueryString(q, "dev");
        // let pcl = util.getQueryString(q, "pcl");
        // if (q.includes('yundian') || pcl === '10041') {
        //   app.globalData.apiUrl = yundianUrl ? yundianUrl : 'https://gmzfb.cnman.cn/v1/wx/';
        //   app.globalData.isZm = false;
        //   // this.globalData.apiUrl = 'https://testapi.cnman.cn/gm/wx/v1/wx/'
        // } else if (q.includes('blue.chinaman.ink')) {
        //   // 二代线
        //   app.globalData.apiUrl = baseUrl ? baseUrl : 'https://zmapi.cnman.cn/v1/wx/';
        //   app.globalData.isBlue = true;
        // } else {
        //   // this.globalData.apiUrl = baseUrl
        //   // this.globalData.apiUrl = "https://zmapi.cnman.cn/test/v1/wx/"
        //   app.globalData.apiUrl = baseUrl ? baseUrl : 'https://zmapi.cnman.cn/v1/wx/';
        // }
        // this.getLoginToken(true);

        this.checkOrderStatus();
        this.getDeviceInfo();
        console.log('app.globalData', app.globalData)
        wx.navigateTo({ url: '/pages/padline/padline' });
      }
    });
  },
  // 服务跳转
  serviceSkip(ev) {
    ev.mark = { id: ev.target.dataset.id }
    console.log('serviceSkip', ev)
    let configJson = this.data.serviceSkipMap[ev.mark.id] || {};
    let serviceDesc = "服务跳转";
    if (configJson.status === 2) serviceDesc = "未开通服务";
    if (configJson.gotoType === 2) serviceDesc = "跳转第三方小程序" + configJson.appId;
    let param = {
      deviceSn: this.data.devInfo.deviceSn,
      appId: this.data.appId,
      serviceType: ev.mark.id,
      serviceDesc: serviceDesc
    };
    API.addServiceLog(param).then(res => {
      console.log("日志记录成功");
    });
    if (configJson.status === 2) return wx.showToast({
      title: '未开通服务',
      icon: 'none'
    });
    if (configJson.gotoType === 2) return wx.navigateToMiniProgram({
      appId: configJson.appId,
      path: configJson.url
    });
    if (ev.mark.id === 1) return this.pageGotoSweep();
    if (ev.mark.id === 2) return this.pageGotoArticles();
    if (ev.mark.id === 3) return this.pageGotoRepair();
    if (ev.mark.id === 4) return this.callService();
    if (ev.mark.id === 5) return this.pageGotoInvoice();
    if (ev.mark.id === 6) return this.getRoomTypeInfo();
    if (ev.mark.id === 7) return this.checkToConfirm();
    if (ev.mark.id === 8) return this.toTicket();
    if (ev.mark.id === 9) return this.getFixedRemindRss();
    if (ev.mark.id === 10) return this.pageComplaints();
    if (ev.mark.id === 11) return this.toSupermarket();
    return wx.showToast({
      title: '未开通服务',
      icon: 'none'
    });
  },
  daysInput(e) {
    let value = e.detail.value;
    let pos = e.detail.cursor;
    value = value !== '' ? parseInt(value) || 1 : value;
    this.data.continueInfo.days = value;
    this.setData({
      continueInfo: this.data.continueInfo
    });
    return {
      value,
      cursor: pos
    };
  },
  daysAdd(e) {
    let days = this.data.continueInfo.days + 1;
    if (days > 999) days = 999;
    this.data.continueInfo.days = days;
    this.setData({
      continueInfo: this.data.continueInfo
    });
  },
  daysSub(e) {
    let days = this.data.continueInfo.days - 1;
    if (days < 1) days = 1;
    this.data.continueInfo.days = days;
    this.setData({
      continueInfo: this.data.continueInfo
    });
  },
  continueInfoClose() {
    this.data.continueInfo.off = false;
    this.setData({
      continueInfo: this.data.continueInfo
    });
  },
  continueInfoCloseNot() {
    return false;
  },
  getRoomTypeInfo() {
    // 速8小程序跳转
    if (this.data.devInfo.projectLabel === 'hotel_super8') {
      // 添加事件
      // wx.reportEvent("super8_xuzhu", {});
      wx.navigateToMiniProgram({
        appId: 'wx9f4e44d702bc36de',
        path: 'pages/hotel/details/index?hotelId=' + this.data.devInfo.hotelId
      });
    } else {
      // wx.reportEvent("service_meituan_xuzhu", {});
      wx.navigateTo({
        url: "/pages/scendPages/serve/conrtnLive/conrtnLive"
      });
    }

    // if (this.data.continueInfo.loading) return
    // this.data.continueInfo.loading = true
    // let params = { placeId: this.data.devInfo.placeId, deviceSn: this.data.devInfo.deviceSn }
    // API.getRoomTypeInfo(params).then(res => {
    //   let { id, price, discountsAmount } = res.result.data || {}
    //   this.data.continueInfo.loading = false
    //   if (!id) return wx.showToast({ title: '未开通服务', icon: 'none' })

    //   this.data.continueInfo.off = true
    //   this.data.continueInfo.price = price
    //   this.data.continueInfo.roomTypeId = id
    //   this.data.continueInfo.discountsAmount = discountsAmount
    //   this.setData({ continueInfo: this.data.continueInfo })
    //   console.log(this.data.continueInfo)
    // }).catch(err => {
    //   this.data.continueInfo.loading = false
    // })
  },

  createRoomOrder() {
    if (this.data.continueInfo.isDisable || !this.data.continueInfo.days) return;
    this.data.continueInfo.isDisable = true;
    let nowTime = new Date().getTime();
    let params = {
      "deviceSn": this.data.devInfo.deviceSn,
      "openid": this.data.loginInfo.openid,
      "roomTypeId": this.data.continueInfo.roomTypeId,
      "inTime": formatTime(new Date(nowTime), '-'),
      "leaveTime": formatTime(new Date(nowTime + 1000 * 60 * 60 * 24 * this.data.continueInfo.days), '-')
    };
    API.createRoomOrder(params).then(res => {
      if (!res.result.pay) return wx.showToast({
        title: '续住失败，请稍后再试',
        icon: 'none'
      });
      this.wxPayment(res.result.pay);
    }).catch(err => {
      this.data.continueInfo.isDisable = false;
    });
  },
  wxPayment(data) {
    let param = JSON.parse(data);
    // wx.requestPayment({
    //   'timeStamp': param.timeStamp,
    //   'nonceStr': param.nonceStr,
    //   'package': param.package,
    //   'signType': param.signType,
    //   'paySign': param.paySign,
    //   'success': res => {
    //     wx.showToast({
    //       title: '续住成功',
    //       icon: 'success'
    //     });
    //     this.setData({
    //       continueInfo: {
    //         off: false
    //       }
    //     });
    //   },
    //   'fail': res => {
    //     wx.showToast({
    //       title: '支付失败',
    //       icon: 'none'
    //     });
    //   },
    //   'complete': res => {
    //     this.data.continueInfo.isDisable = false;
    //   }
    // });
  },
  // 早餐券
  toTicket() {
    wx.showToast({
      title: '即将上线，敬请期待',
      icon: 'none'
    });
  },
  // 退房确认
  checkToConfirm() {
    wx.navigateTo({
      url: "/pages/serviceHome/checkOut/checkOut"
    });
    // pages/serviceHome/checkOut/checkOut
    // wx.showModal({
    //   title: '退房确认',
    //   content: `客房 ${this.data.devInfo.room} 用户您好，现在为您办理退房手续，如继续请点击确定！退房成功后，请将房卡退还于前台~`,
    //   confirmText: '确定',
    //   cancelColor: '#333',
    //   confirmColor: '#00A49A',
    //   success: (res) => {
    //     if (res.confirm) {
    //       this.checkToNotification()
    //     } else if (res.cancel) {
    //       console.log('用户点击取消')
    //     }
    //   }
    // })
  },

  // 退房通知
  checkToNotification() {
    let {
      placeId,
      placeName,
      deviceSn,
      room
    } = this.data.devInfo;
    let param = {
      "notificationType": 7,
      placeId,
      placeName,
      deviceSn,
      "memberPhone": this.data.loginInfo.phone,
      "placeRoom": room,
      "info": '退房通知',
      "makeTime": '1970-01-01'
    };
    API.cleanFormSubmit(param).then(res => {
      wx.showToast({
        title: '提交成功,感谢您的使用！',
        icon: 'none'
      });
    });
  },
  // 呼叫服务
  callAllService() {
    wx.showModal({
      title: '呼叫服务',
      content: `客服联系热线：${util.PHONE_NUMBER}`,
      confirmText: '立即呼叫',
      cancelColor: '#666',
      confirmColor: '#00A49A',
      success: res => {
        if (res.confirm) {
          this.makePhoneCall(util.PHONE_NUMBER);
        } else if (res.cancel) {
          console.log('用户点击取消');
        }
      }
    });
  },
  // 呼叫服务
  callService() {
    if (!this.data.devInfo.serviceCall) return wx.showToast({
      title: '无服务电话',
      icon: 'error'
    });
    wx.showModal({
      title: '呼叫服务',
      content: `客服联系热线：${this.data.devInfo.serviceCall}`,
      confirmText: '立即呼叫',
      cancelColor: '#666',
      confirmColor: '#00A49A',
      success: res => {
        if (res.confirm) {
          this.makePhoneCall(this.data.devInfo.serviceCall);
        } else if (res.cancel) {
          console.log('用户点击取消');
        }
      }
    });
  },
  // 拨打电话
  makePhoneCall(phone) {
    wx.makePhoneCall({
      phoneNumber: phone,
      fail: err => {
        wx.showToast({
          title: '拨打电话失败',
          icon: 'none'
        });
      }
    });
  },
  // 登录
  getLoginToken(value) {
    API.getLoginToken().then(res => {
      if (!res) return;
      let loginInfo = res.result;
      this.setData({
        loginInfo: loginInfo
      });
      wx.setStorageSync("login_key", loginInfo);
      wx.setStorageSync("host", res.result.host);
      this.checkOrderStatus();
      this.getDeviceInfo(value);
    });
  },
  // 检查是否有订单
  checkOrderStatus() {
    let param = {
      "deviceSn": app.globalData.deviceSn,
      "openid": this.data.loginInfo.openid
    };
    API.checkOrderStatus(param).then(res => {
      const orderInfo = res.result;
      orderInfo.deviceSn = app.globalData.deviceSn;
      this.setData({
        orderInfo: orderInfo
      });
      this.computeOrderCost();
    });
  },
  // 获取设备信息
  getDeviceInfo(value) {
    // isSteward != 1 客房服务暂未开通
    let param = {
      "deviceSn": app.globalData.deviceSn
    };
    API.getRoomDeviceInfo(param).then(res => {
      if (value && res.result.isSteward != 1) {
        wx.redirectTo({
          url: '/pages/padline/padline'
        });
      }
      app.setBluetoothMac(res.result.bluetoothMac);
      app.setBluetoothType(res.result);
      this.setData({
        devInfo: res.result
      });
      wx.setStorageSync("showAd", res.result.isAd);
      this.computeOrderCost();
      computeOrderCostTime = setInterval(this.computeOrderCost.bind(this), 1000);
      this.setData({
        showPage: true
      });
      this.setHotServiceList(res.result.serviceConfig);
      this.setServiceShow(res.result.serviceConfig);
      this.getPlaceBulletin();
      this.getNoticeInfo();
      const {
        address,
        placeName,
        room,
        deviceSn,
        placeId
      } = res.result;
      const params = {
        address,
        placeName,
        room,
        deviceSn,
        placeId
      };
      wx.setStorageSync("baseInfo", params);
      console.log("参数====》", params);
      // this.getGoodsTypeInfo(placeId)
    });
  },

  getPlaceBulletin() {
    let param = {
      "placeId": parseInt(this.data.devInfo.placeId)
    };
    API.getPlaceBulletin(param).then(res => {
      this.setData({
        bulletin: res.result
      });
    });
  },
  /**
   * 设置服务展示
   * 服务类型
   * 1-清扫 2-日用品更换 3-维修 4-呼叫服务 5-开票服务 6-续住 7-退房 8-电子优惠券
   * 9-好评有礼 10-投诉建议 11-客房超市 12-叫醒服务 13-售货机补货
   */
  setServiceShow(config) {
    let list = [];
    let targetList = [];
    let initList = [
    // { name: '好评有礼', id: 9 },
    {
      name: '联系前台',
      id: 4
    }, {
      name: '清扫服务',
      id: 1
    }, {
      name: '客房送物',
      id: 2
    }, {
      name: '维修服务',
      id: 3
    }, {
      name: '预约开票',
      id: 5
    }, {
      name: '续住服务',
      id: 6
    },
    // { name: '叫醒服务', id: 12 },
    {
      name: '酒店超市',
      id: 11
    }, {
      name: '在线退房',
      id: 7
    },
    // { name: '电子早餐券', id: 8 },
    {
      name: '投诉建议',
      id: 10
    }];
    try {
      list = JSON.parse(config);
      for (let item1 of list) {
        this.data.serviceSkipMap[item1.id] = item1;
        for (let item of initList) {
          if (item.id === item1.id && item1.status === 1) {
            item1.name = item.name;
            targetList.push(item);
          }
        }
      }
      const serviceMenuList = [];
      const targetListCopy = JSON.parse(JSON.stringify(targetList));
      const time = Math.ceil(targetList.length / 8);
      for (let i = 0; i < time; i++) {
        let arr = [];
        arr = i === time - 1 ? targetListCopy : targetListCopy.splice(0, 8);
        serviceMenuList.push(arr);
      }
      this.setData({
        serviceList: targetList,
        serviceMenuList
      });
    } catch (e) {
      list = initList;
      const serviceMenuList = [];
      const targetListCopy = JSON.parse(JSON.stringify(initList));
      const time = Math.ceil(targetListCopy.length / 8);
      for (let i = 0; i < time; i++) {
        let arr = [];
        arr = i === time - 1 ? targetListCopy : targetListCopy.splice(0, 8);
        serviceMenuList.push(arr);
      }
      this.setData({
        serviceList: targetList,
        serviceMenuList
      });
    }
    // console.log("list===>", list)
    // this.setData({ serviceList: targetList })
  },

  // 设置热点服务
  setHotServiceList(list) {
    list = list ? list : '[]';
    list = JSON.parse(list);
    list = list.filter(item => item.type === 2);
    const initList = new Map([[13, {
      name: '手机充电',
      id: 13,
      largeImg: '',
      smallImg: ''
    }], [14, {
      name: '情侣用品',
      id: 14,
      largeImg: '',
      smallImg: ''
    }], [6, {
      name: '特惠续住',
      id: 6,
      largeImg: '',
      smallImg: ''
    }], [9, {
      name: '好评有礼',
      id: 9,
      largeImg: '',
      smallImg: ''
    }], [15, {
      name: '客房WiFi',
      id: 15,
      largeImg: '',
      smallImg: ''
    }]]);
    const hotServiceList = [];
    for (let item of list) {
      if (initList.has(item.id)) {
        hotServiceList.push(initList.get(item.id));
      }
    }
    console.log('list', list);
    this.setData({
      hotServiceList
    });
  },
  // 计算订单时长与费用
  computeOrderCost() {
    if (this.data.orderInfo.state !== 2 || !this.data.devInfo.id || !this.data.orderInfo.id) {
      return clearInterval(computeOrderCostTime);
    }
    let timeLen = parseInt(new Date().getTime() / 1000 - this.data.orderInfo.beginAt);
    timeLen = timeLen > 0 ? timeLen : 0;
    let {
      h,
      m,
      s
    } = util.secondToTime(timeLen > 0 ? timeLen : 0);
    let t = `${h}时${m}分${s}秒`;
    let money = 0;
    for (let item of this.data.devInfo.ruleInfo) if (item.productId === this.data.orderInfo.productId) {
      if (this.data.orderInfo.feeMode === 1) {
        money = item.payIntervalPrice / (item.payInterval * 60) * timeLen;
        if (money > item.maxPayPrice) money = item.maxPayPrice;
        money = (money / 100).toFixed(2);
      } else money = (item.useDuration / 100).toFixed(2);
      break;
    }
    this.setData({
      orderCost: {
        t,
        money
      }
    });
  },
  // 蓝牙通知
  openBluetoothAdapterPeripheral(targetPowerMinute) {
    openBluetoothAdapterPeripheral({
      bluetoothMac: app.globalData.bluetoothMac,
      powerMinute: targetPowerMinute,
      success: res => {
        console.log('startAdvertising', res);
      }
    });
  },
  // 结束订单，结束使用
  closeOrder: function () {
    let loginInfo = wx.getStorageSync('login_key');
    wx.showModal({
      title: '小电温馨提示',
      content: '安全用电提醒：充电完毕后，请记得切断电源，将充电线放回方盒。它安全、您安心！充一次、美一次!',
      cancelText: '继续使用',
      confirmText: '立即归还',
      cancelColor: '#666',
      confirmColor: '#00A49A',
      success: res => {
        if (!res.confirm) return;
        let param = {
          "deviceSn": app.globalData.deviceSn,
          "productId": this.data.orderInfo.productId,
          "openid": loginInfo.openid,
          "tradeNo": this.data.orderInfo.tradeNo
        };
        API.closeOrder(param).then(res => {
          if (app.globalData.bluetoothMac) this.openBluetoothAdapterPeripheral(1);
          wx.redirectTo({
            url: `/pages/mine/orderdetail/orderdetail?deviceSn=${param.deviceSn}&tradeNo=${param.tradeNo}&state=5`
          });
        });
      }
    });
  },
  // 立即充电/继续充电
  orderToBack() {
    // wx.reportEvent("service_meituan_chongdian", {});
    let serviceDesc = "充电服务";
    if (this.data.orderInfo.state === 2) serviceDesc = serviceDesc + "继续使用";
    let param = {
      deviceSn: this.data.devInfo.deviceSn,
      appId: this.data.appId,
      serviceType: 88,
      serviceDesc: serviceDesc
    };
    API.addServiceLog(param).then(res => {
      console.log("日志记录成功");
    });
    if (this.data.orderInfo.state === 2) {
      return wx.redirectTo({
        url: '/pages/cuse/cuse?devicesn=' + app.globalData.deviceSn
      });
    }
    return wx.redirectTo({
      url: '/pages/padline/padline?devicesn=' + app.globalData.deviceSn
    });
  },
  // // 查询商品类型
  // getGoodsTypeInfo(placeId) {
  //   API.getGoodsType({ placeId }).then(res => {
  //     this.setData({
  //       goodsType: res.result
  //     })
  //   })
  // },
  // 页面跳转
  pageGoto(url) {
    let info = {
      tradeNo: this.data.orderInfo.tradeNo || null,
      deviceSn: this.data.orderInfo.deviceSn || null,
      adderss: this.data.devInfo.room || null,
      placeId: this.data.devInfo.placeId || null,
      memberPhone: this.data.loginInfo.phone || null,
      placeName: this.data.devInfo.placeName || null
    };
    url = url + '?info=' + JSON.stringify(info);
    // console.log(url)
    // wx.redirectTo({url})
    wx.navigateTo({
      url
    });
  },
  pageGotoSweep() {
    this.pageGoto("/pages/scendPages/serve/clean/clean");
  },
  pageGotoRepair() {
    this.pageGoto("/pages/scendPages/serve/repair/repair");
  },
  pageGotoArticles() {
    this.pageGoto("/pages/scendPages/serve/articles/articles");
  },
  pageGotoInvoice() {
    this.pageGoto("/pages/scendPages/serve/invoice/invoice");
  },
  pageGotoGoodComent() {
    // wx.reportEvent("event_haoping", {});
    this.pageGoto("/pages/evaluateGift/evaluateGift");
  },
  pageComplaints() {
    this.pageGoto("/pages/home/suggestions/suggestions");
  },
  toSupermarket() {
    // const { goodsType } = this.data
    // if (!goodsType || goodsType.length === 0) {
    //   wx.showToast({
    //     title: "未配置",
    //     icon: "none"
    //   })
    //   return
    // }
    this.pageGoto("/pages/supermarket/supermarket/supermarket");
  },
  // 租车
  thirdPageGotoRentCar() {
    // wx.reportEvent("service_meituan_zuche", {});
    wx.navigateToMiniProgram({
      appId: 'wxe4bc565cbbf5e289',
      path: 'pages/isd/indexNew/index'
    });
  },
  // 火车票
  thirdPageGotoTicket() {
    // wx.reportEvent("service_meituan_huochepiao", {});
    wx.navigateToMiniProgram({
      appId: 'wx0e6ed4f51db9d078',
      path: 'pages/train/index/index'
    });
  },
  // 机票
  thirdPageGotoFlight() {
    // wx.reportEvent("service_meituan_jipiao", {});
    wx.navigateToMiniProgram({
      appId: 'wx336dcaf6a1ecf632',
      path: 'page/home/index/index?wxrefid=1942670974&tab=1&appid=wx336dcaf6a1ecf632'
    });
  },
  // 汽车票
  thirdPageGotoCar() {
    // wx.reportEvent("service_meituan_qichepiao", {});
    wx.navigateToMiniProgram({
      appId: 'wx0e6ed4f51db9d078',
      path: 'pages/bus/index/index'
    });
  },
  // 美团外卖
  thirdPageGotoMeituan() {
    // wx.reportEvent("service_meituan_waimai", {});
    wx.navigateToMiniProgram({
      appId: 'wx2c348cf579062e56',
      path: 'pages/padline/padline'
    });
  },
  // 周边游
  thirdPageGotoTour() {
    // wx.reportEvent("service_meituan_zhoubianyou", {});
    wx.navigateToMiniProgram({
      appId: 'wx0e6ed4f51db9d078',
      path: 'pages/tour/list/list'
    });
  },
  // 景点门票
  thirdPageGotoScenic() {
    // wx.reportEvent("service_meituan_menpiao", {});
    wx.navigateToMiniProgram({
      appId: 'wx0e6ed4f51db9d078',
      path: 'pages/ticket/list/list'
    });
  },
  // 足浴
  thirdPageGotoLavipeditum() {
    // wx.reportEvent("service_meituan_sanazuyu", {});
    if (this.data.devInfo.city === '武汉市') {
      wx.navigateTo({
        url: '/pages/webview/wyWebview/wyWebview'
      });
    } else if (this.data.devInfo.city === '衡阳市') {
      wx.navigateTo({
        url: '/pages/webview/eyWebview/eyWebview'
      });
    } else if (this.data.devInfo.city === '南宁市') {
      wx.navigateTo({
        url: '/pages/webview/xmNnWebview/xmNnWebview'
      });
    } else {
      wx.showToast({
        title: "目前该城市暂不支持",
        icon: "none"
      });
      return;
    }
  },
  toZm: function () {
    wx.navigateTo({
      url: '/pages/zsjm/zsjm'
    });
    // wx.navigateTo({ url: '/pages/wifizs/wifizs', })
  },

  navNotice() {
    wx.navigateTo({
      url: '/pages/home/notice/notice'
    });
  },
  toSuper: function () {
    // wx.reportEvent("super8_home_banner", {});
    wx.navigateTo({
      url: '/pages/mine/super/super'
    });
  },
  toFZAPP: function () {
    // wx.reportEvent("hz_fz_banner", {}); // 杭州反诈弹框
    wx.navigateTo({
      url: '/pages/webview/hzFzWebview/hzFzWebview'
    });
  },
  toAnmo: function () {
    wx.navigateTo({
      url: '/pages/webview/eyWebview/eyWebview'
    });
  },
  toXmNn: function () {
    wx.navigateTo({
      url: '/pages/webview/xmNnWebview/xmNnWebview'
    });
  },
  closeFzWindow: function () {
    this.setData({
      isShow: false
    });
  }
});
